package com.cbg.runner;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cbg.base.constant.Constant;
import com.cbg.base.utils.SpringContextHolder;
import com.cbg.sys.entity.Line;
import com.cbg.sys.entity.LineIni;
import com.cbg.sys.service.ILineCarService;
import com.cbg.sys.service.ILineService;
import com.cbg.sys.utils.LineUtils;
import org.springframework.data.redis.core.RedisTemplate;
import java.time.LocalDate;
import java.util.List;
/**
 * <pre>0点定时任务</pre>
 * <small> 2018-12-15 | chenbing </small>
 */
public class CronTask {
    public void run(){
        ILineService lineService = SpringContextHolder.getBean(ILineService.class);
        RedisTemplate<String,Line> lineRedisTemplate= SpringContextHolder.getBean("lineRedisTemplate");
        ILineCarService lineCarService = SpringContextHolder.getBean(ILineCarService.class);
        lineRedisTemplate.delete(lineRedisTemplate.keys(Constant.LINE_SUFFIX+"*"));
        lineService.updateBatchById(lineService.list());
        LocalDate afterTomorrow = LocalDate.now().plusDays(2);
        List<LineIni> afterTomorrowInis;
        List<Line> afterTomorrowLines;
        if((afterTomorrowInis = new LineIni().selectList(new LambdaQueryWrapper<LineIni>()
                .eq(LineIni::getIsDone,0).eq(LineIni::getDateIn,afterTomorrow))).size()<1){
            if((afterTomorrowInis = new LineIni().selectList(new LambdaQueryWrapper<LineIni>()
                    .eq(LineIni::getType,afterTomorrow.getDayOfWeek().getValue() < 6 ? 0 : 1))).size()<1)
                afterTomorrowInis=new LineIni().selectList(new LambdaQueryWrapper<LineIni>().eq(LineIni::getType,0));
        }
        if((afterTomorrowLines= LineUtils.createLinesByInis(afterTomorrowInis,afterTomorrow)).size()>0)
            lineService.saveOrUpdateBatch(afterTomorrowLines);
        lineCarService.planTypeAndCar(afterTomorrowLines);
        LineUtils.putLinesIn3DaysToRedis(lineService.linesOf3Days());
    }
}
